import 'package:flutter/material.dart';
import '../models/word.dart';
import '../services/database_service.dart';

class AddWordScreen extends StatefulWidget {
  const AddWordScreen({super.key});

  @override
  _AddWordScreenState createState() => _AddWordScreenState();
}

class _AddWordScreenState extends State<AddWordScreen> {
  final _formKey = GlobalKey<FormState>();
  final _wordController = TextEditingController();
  final _meaningController = TextEditingController();
  final _exampleController = TextEditingController();
  final DatabaseService _databaseService = DatabaseService();
  
  List<Map<String, dynamic>> _categories = [];
  int? _selectedCategoryId;

  @override
  void initState() {
    super.initState();
    _loadCategories();
  }

  Future<void> _loadCategories() async {
    final categories = await _databaseService.getCategories();
    setState(() {
      _categories = categories;
    });
  }

  Future<void> _saveWord() async {
    if (_formKey.currentState!.validate()) {
      final word = Word(
        word: _wordController.text,
        meaning: _meaningController.text,
        example: _exampleController.text.isEmpty ? null : _exampleController.text,
        categoryId: _selectedCategoryId,
      );

      await _databaseService.insertWord(word);
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加新单词'),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            TextFormField(
              controller: _wordController,
              decoration: const InputDecoration(
                labelText: '单词',
                border: OutlineInputBorder(),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入单词';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _meaningController,
              decoration: const InputDecoration(
                labelText: '含义',
                border: OutlineInputBorder(),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入含义';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _exampleController,
              decoration: const InputDecoration(
                labelText: '例句（可选）',
                border: OutlineInputBorder(),
              ),
              maxLines: 2,
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<int>(
              value: _selectedCategoryId,
              decoration: const InputDecoration(
                labelText: '选择分类',
                border: OutlineInputBorder(),
              ),
              items: [
                const DropdownMenuItem<int>(
                  value: null,
                  child: Text('无分类'),
                ),
                ..._categories.map((category) => DropdownMenuItem<int>(
                  value: category['id'],
                  child: Row(
                    children: [
                      CircleAvatar(
                        backgroundColor: Color(int.parse(category['color'].substring(2), radix: 16)),
                        radius: 8,
                      ),
                      const SizedBox(width: 8),
                      Text(category['name']),
                    ],
                  ),
                )).toList(),
              ],
              onChanged: (value) {
                setState(() {
                  _selectedCategoryId = value;
                });
              },
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              onPressed: _saveWord,
              child: const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text('保存'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _wordController.dispose();
    _meaningController.dispose();
    _exampleController.dispose();
    super.dispose();
  }
}